import Taro from '@tarojs/taro'
import { uploadAuthURL } from './constants'
import COS from 'cos-js-sdk-v5'
// import CryptoJS from 'crypto-js'
import _isEmpty from 'lodash/isEmpty'
import _findIndex from 'lodash/findIndex'

export const phoneReg = /^1[3456789]\d{9}$/i
export const cityReg = /.+?(省|市|自治区|自治州|县|区)/g;
export const specialCityReg = /^(上海|北京|重庆|天津)/g;
/** 分割省市区 */
export function divisionCityStr(str){
	let obj = {}
	if(str){
		const arr = str.match(cityReg)
		if(specialCityReg.test(str) && arr.length === 2){
			obj = {
				provinceCn: arr[0] || '',
				cityCn: arr[0] || '',
				districtCn: arr[1] || '',
			}
		}else{
			obj = {
				provinceCn: arr[0] || '',
				cityCn: arr[1] || '',
				districtCn: arr[2] || '',
			}
		}
		console.log('objg===', obj)
	}

	return obj
}

/** 手机号验证 */
export function phoneVerify(phone){
	return phoneReg.test(phone)
}

/**获取code */
export function getQueryString(name){
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
	var r = window.location.search.substr(1).match(reg);
	if (r != null) return unescape(r[2]);
	return null;
}

/**
 * 上传服务器
 * @param {*} type
 * @param {*} callback
 */
export const upload2server = (complete) =>{
	Taro.request({
		url: uploadAuthURL,
		method: 'POST',
		data: {}
	}).then((res) => {
		const data = res.data
		let cos = new COS({
			getAuthorization: (options, callback) => {
				// 异步获取临时密钥
				callback({
					TmpSecretId: data.tmpsecretid,
					TmpSecretKey: data.tmpsecretkey,
					XCosSecurityToken: data.sessiontoken,
					ExpiredTime: data.expiredTime,

				});
			}
		})
		complete && complete(cos, data)
	}).catch(err => {
		console.log("cos error ==",err)
	});
}

/** blob字符串转blob对象 */
export const convertObjectUrlToBlob = url => {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    xhr.open('GET', url, true)
    xhr.responseType = 'blob'
    xhr.onload = function (e) {
      if (this.status === 200) {
        resolve(this.response)
      } else {
        /* eslint-disable prefer-promise-reject-errors */
        reject({ status: this.status })
      }
    }
    xhr.send()
	})
}

/** 15天的预约时间+小时*/
export function getDaysList(len=3){
  let dateList = []
  for(let i=0; i<len; i++){
    let date = new Date()
		date.setDate(date.getDate() + i) //获取Day天后的日期

    const y = date.getFullYear()
    let m = date.getMonth()+1
    m = m>9 ? m : '0'+m
    let d = date.getDate()
    d = d>9 ? d : '0'+d
    const time = y+'-'+m+'-'+d
    dateList.push(time)
  }
  return dateList
}

/**
 * dateList 同 getDaysList 方法返回
 * @param {*} dateList
 * @param {*} date
 */
export function getDayIndex(dateList, date) {
	return _findIndex(dateList, function(o){return o == date})
}

/** 当天为3小时，其他时间为24小时 */
export function getHoursList(index){
	let time = []
	const date = new Date()
	const hour = date.getHours()+1
  const start = index===0 && hour+3<23 ? hour+3 : 0
  for(let i=0; i<=23; i++){

		const dh = i<10 ? '0'+i+'' : i+''
    time.push({name: dh})
  }
  return time
}

export function getCommonHoursList(){
	let hour = []
  for(let i=0; i<=23; i++){
		const dh = i<10 ? '0'+i+'' : i+''
    hour.push(dh)
  }
  return hour
}

/** 60分钟 */
export function getMinutesList(){
	let time = []
	for(let i=0, len=60; i<len; i++){
		const dh = i<10 ? '0'+i+'' : i+''
		time.push(dh)
	}
	return time
}

export function getTimeDown(start, end){
	let tdata = {}
	return tdata
}

/**
 * 额外支付倒计时
 */
export function getPayDownTime(rInfo) {
	let time = {};
	if (rInfo.orderStatusEn === "processes") {
		let pd = rInfo.logs[0].orderAddedMoneyDown;
		if (pd) {
			pd = pd.split(':');
			time = {
				minute: parseInt(pd[0]),
				second: parseInt(pd[1])
			};
		}
	}
	return time;
}

/**
 * 完成订单倒计时
 * @param {*} rInfo
 */
export function getOrderDownTime(rInfo) {
	let time = {};
	if (rInfo.orderStatusEn === 'finish') {
		let pd = rInfo.awaitingConfirmTimeDown;
		if (pd) {
			pd = pd.split(':');
			time = {
				hour: parseInt(pd[0]),
				minute: parseInt(pd[1]),
				second: parseInt(pd[2])
			};
		}
	}
	return time;
}

/**
 * 等待接单倒计时
 * @param {*} rInfo
 */
export function getWaitingTime(rInfo){
	let time = {}
	if(!_isEmpty(rInfo) && rInfo.orderStatusEn === 'waiting'){
		/**
			new Date(time)
				iOS 不兼容YYYY-MM—DD HH:mm:ss, 只能使用YYYY/MM/DD HH:ss:mm,
				Android兼容两种模式
		**/
		const endTime = rInfo.takingEndTime.replace(/\-/g, '/');
		let now = new Date().getTime()

		let end = new Date(endTime).getTime()
		const diff = end - now
		if(diff >= 0){
			 //计算出相差天数

			const days = Math.floor(diff/(24*3600*1000));
			//计算出小时数
			const leave1 = diff%(24*3600*1000);    //计算天数后剩余的毫秒数
			const hours = parseInt(Math.floor(leave1/(3600*1000))) + parseInt(days) * 24;
			//计算相差分钟数
			const leave2 = leave1%(3600*1000);        //计算小时数后剩余的毫秒数
			const minutes = Math.floor(leave2/(60*1000));

			//计算相差秒数
			const leave3 = leave2%(60*1000);      //计算分钟数后剩余的毫秒数
			const seconds = Math.round(leave3/1000);

			time = { hours, minutes, seconds }
		}
	}
	return time
}

/** 等待接单是否超过20分钟 */
export function checkOrderOver20(rInfo){
	let isOver = false;
	const startTime = rInfo.takingStartTime.replace(/\-/g, '/');
	let now = new Date().getTime()

	let start = new Date(startTime).getTime()
	const diff = now - start

	if(diff >= 0 && rInfo.orderStatusEn === 'waiting'){
		 //计算出相差天数
		 const days = Math.floor(diff/(24*3600*1000));
		//计算出小时数
		const leave1 = diff%(24*3600*1000);    //计算天数后剩余的毫秒数
		const hours = parseInt(Math.floor(leave1/(3600*1000))) + parseInt(days) * 24;
		//计算相差分钟数
		const leave2 = leave1%(3600*1000);     //计算小时数后剩余的毫秒数
		const minutes = Math.floor(leave2/(60*1000));
		if(minutes > 20){
			isOver = true;
		}else{
			if(hours>0 || days > 0){
				isOver = true;
			}
		}
	}
	return isOver
}


/*
* 图片压缩
* @
* */
export function compressImage(file) {
	return new Promise((resolve, reject) => {
		const reader = new FileReader(), img = new Image();
		const maxSize = 5 * 1024 * 1024; // 最大设置为5M
		reader.readAsDataURL(file);
		reader.onload = function () {
			img.src = this.result;
		};
		const canvas = document.createElement('canvas');
		const context = canvas.getContext('2d');
		img.onload = function () {
			const originWidth = this.width, originHeight = this.height;
			const maxWidth = 720, maxHeight = 720;
			let targetWidth = originWidth, targetHeight = originHeight;
			// 图片尺寸超过720x720的限制
			if (originWidth > maxWidth || originHeight > maxHeight) {
				if (originWidth / originHeight > maxWidth / maxHeight) {
					targetWidth = maxWidth;
					targetHeight = Math.round(maxWidth * (originHeight / originWidth));
				} else {
					targetHeight = maxHeight;
					targetWidth = Math.round(maxHeight * (originWidth / originHeight));
				}
			}

			canvas.width = targetWidth;
			canvas.height = targetHeight;
			// 清除画布
			context.clearRect(0, 0, targetWidth, targetHeight);
			// 图片压缩
			context.drawImage(img, 0, 0, targetWidth, targetHeight);
			const dataurl = canvas.toDataURL('image/png');
			// console.log('原始尺寸===', originWidth, originHeight);
			// console.log('压缩尺寸===', targetWidth, targetHeight);
			const blobObj = dataURLtoBlob(dataurl);
			// const fileObj = dataURLtoFile(dataurl, file.name)
			// console.log('转化图片=blob==', blobObj);
			// console.log('转化图片=file==', fileObj)
			resolve(blobObj);
			// canvas.toBlob((blob) => {
			//     resolve(blob)
			// }, file.type || 'image/png')
		}
	})
}

/**
 * dataurl to blob
 * @param dataurl 二进制图片
 */
function dataURLtoBlob(dataurl) {
	let arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
		bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new Blob([u8arr], {type: mime});
}

/**
* dataul to File
* @param dataurl	二进制图片
* @param filename 文件name
*/
function dataURLtoFile(dataurl, filename) {
	let arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1];
		bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new File([u8arr], filename, {type: mime});
}

export function handleConditionName(name){
	let nt = ''
	if(name && name !== '全部' && name !== '全国'){
		nt = name
		if(name.length > 4){
			nt = name.substring(0,3) + '...'
		}
	}
	return nt
}

export function generateQueryString (url, options) {
	if (!options) {
		return url
	}
	var tempArr = []
	for (var key in options) {
		var param = `${key}=${options[key]}`
		tempArr.push(param)
	}
	return encodeURIComponent(url + '?' + tempArr.join('&'))
}

/** 获取增值服务文字 */
export function getSelectFromArray(list){
	let str = ''
	if(!_isEmpty(list)){
		list.forEach(ld => {
			if(ld.checked){
				str = str + ' ' + ld.name
			}
			if(!_isEmpty(ld.childs)){
				ld.childs.forEach(cd => {
					if(cd.checked){
						str = str + ' ' + cd.name
					}
				})
			}
		})
	}
	return str
}


/**
 * 生成随机数
 * @param {*} len   长度
 * @param {*} radix 基数
 */
export function getRandomNum(len=6, radix) {
  let chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  let uuid = [],i;
  radix = radix || chars.length;
  if (len) {
    for (i = 0; i < len; i++){
      uuid[i] = chars[0 | Math.random() * radix];
    } 
  } else {
    let r;
    uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
    uuid[14] = '4';
    for (i = 0; i < 36; i++) {
      if (!uuid[i]) {
        r = 0 | Math.random() * 16;
        uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
      }
    }
  }
  return uuid.join('');
}

/** 移除下单缓存数据 */
export function removeStorageOrderData(){ 
	Taro.removeStorageSync('traffic_goods_info')				// 货物信息
	Taro.removeStorageSync('traffic_goods_premium')			// 保价费
	Taro.removeStorageSync('traffic_goods_addService')	// 选择的增值服务
	Taro.removeStorageSync('map_select_city')						// 地图选择城市
	Taro.removeStorageSync('address_info_sender')				// 寄件人
	Taro.removeStorageSync('address_info_receiver')			// 收件人
	Taro.removeStorageSync('address_add_info')					// 新增地址
	Taro.removeStorageSync('address_addselect_info')		// 新增选择地址
	Taro.removeStorageSync('address_edit_info')					// 编辑地址
	Taro.removeStorageSync('traffic_line_addService')  // 线路提供增值服务
}